package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"person/models/mysql"
	"person/pkg"
	"time"

	"person/wechatrpc/internal/svc"
	"person/wechatrpc/wechatrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type WeChatRegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewWeChatRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WeChatRegisterLogic {
	return &WeChatRegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *WeChatRegisterLogic) WeChatRegister(in *wechatrpc.WeChatRegisterRequest) (*wechatrpc.WeChatRegisterResponse, error) {
	// todo: add your logic here and delete this line

	var findWeChar mysql.WeChat
	err := findWeChar.FindWeChatByTel(mysql.DB, in.Tel)
	if err != nil {
		return nil, err
	}
	if findWeChar.ID != 0 {
		return nil, errors.New("该手机号已注册,请重试")
	}
	weChat := &mysql.WeChat{
		Tel:        in.Tel,
		Password:   pkg.Md5(in.Password),
		Qq:         in.Qq,
		Email:      in.Email,
		WeChatCode: fmt.Sprintf("wx%d%d", time.Now().Unix(), rand.Intn(10000)),
	}
	err = weChat.WeChatAdd(mysql.DB)
	if err != nil {
		return nil, err
	}

	return &wechatrpc.WeChatRegisterResponse{
		UserId: int64(weChat.ID),
	}, nil
}
